<template>
	<div class="login-container">
		<!-- 背景图 -->
		<div class="background-image"></div>

		<!-- 登录注册框 -->
		<div class="auth-box">
			<!-- 大标题 -->
			<h1 class="system-title">外卖平台管理系统</h1>

			<el-tabs v-model="activeTab" class="auth-tabs" stretch @tab-click="handleTabChange">
				<el-tab-pane label="登录" name="login">
					<!-- 角色选择（仅登录页面显示） -->
					<div class="role-selection" v-if="!showPhoneLogin">
						<el-radio-group v-model="loginForm.role" size="large">
							<el-radio-button label="shopmanager">店长</el-radio-button>
							<el-radio-button label="admin">管理员</el-radio-button>
						</el-radio-group>
					</div>

					<!-- 账号密码登录 -->
					<el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" v-if="!showPhoneLogin">
						<el-form-item prop="username">
							<el-input v-model="loginForm.username" placeholder="用户名/邮箱" prefix-icon="User" />
						</el-form-item>
						<el-form-item prop="password">
							<el-input v-model="loginForm.password" type="password" placeholder="密码" prefix-icon="Lock"
								show-password />
						</el-form-item>

						<el-form-item>
							<el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
							<div class="login-switch">
								<el-link type="primary" :underline="false" class="forgot-password">
									忘记密码?
								</el-link>
								<el-link type="primary" :underline="false" @click="showPhoneLogin = true">
									手机号登录 &gt;
								</el-link>
							</div>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" class="auth-button short-button" @click="handleLogin">
								登录
							</el-button>
						</el-form-item>
					</el-form>

					<!-- 手机号验证码登录 -->
					<el-form :model="phoneLoginForm" :rules="phoneLoginRules" ref="phoneLoginFormRef"
						v-if="showPhoneLogin">
						<el-form-item prop="phone">
							<el-input v-model="phoneLoginForm.phone" placeholder="手机号" prefix-icon="Iphone" />
						</el-form-item>
						<el-form-item prop="captcha">
							<div class="captcha-input">
								<el-input v-model="phoneLoginForm.captcha" placeholder="验证码" prefix-icon="Key" />
								<el-button class="get-captcha-btn" :disabled="captchaDisabled" @click="getCaptcha">
									{{ captchaBtnText }}
								</el-button>
							</div>
						</el-form-item>

						<el-form-item>
							<div class="login-switch">
								<el-link type="primary" :underline="false" @click="showPhoneLogin = false">
									&lt; 返回账号登录
								</el-link>
							</div>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" class="auth-button short-button" @click="handlePhoneLogin">
								登录
							</el-button>
						</el-form-item>
					</el-form>
				</el-tab-pane>

				<el-tab-pane label="注册" name="register">
					<el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
						<el-form-item prop="username">
							<el-input v-model="registerForm.username" placeholder="用户名" prefix-icon="User" />
						</el-form-item>
						<el-form-item prop="email">
							<el-input v-model="registerForm.email" placeholder="邮箱" prefix-icon="Message" />
						</el-form-item>
						<el-form-item prop="phoneNumber">
							<el-input v-model="registerForm.phoneNumber" placeholder="手机号" prefix-icon="Iphone" />
						</el-form-item>
						<el-form-item prop="password">
							<el-input v-model="registerForm.password" type="password" placeholder="密码"
								prefix-icon="Lock" show-password />
						</el-form-item>
						<el-form-item prop="confirmPassword">
							<el-input v-model="registerForm.confirmPassword" type="password" placeholder="确认密码"
								prefix-icon="Lock" show-password />
						</el-form-item>
						<el-form-item>
							<el-button type="primary" class="auth-button short-button" @click="handleRegister">
								注册
							</el-button>
						</el-form-item>
					</el-form>
				</el-tab-pane>
			</el-tabs>

			<div class="third-party-auth">
				<div class="divider">
					<span class="divider-text">或使用第三方登录</span>
				</div>
				<div class="oauth-icons">
					<el-icon :size="24" class="oauth-icon"><svg viewBox="0 0 1024 1024">
							<path
								d="M512 1024C229.222 1024 0 794.778 0 512S229.222 0 512 0s512 229.222 512 512-229.222 512-512 512zm189.632-334.528c0-52.928-2.496-103.36-7.04-151.296h176.96v-215.68h-225.28v-89.152h-89.152v89.152h-89.152v89.152h89.152v246.784c-14.08 71.04-58.432 106.56-117.568 106.56-35.2 0-65.472-11.616-89.152-34.816-23.68-23.232-35.648-53.504-35.648-89.152 0-35.648 11.968-65.92 35.648-89.152 23.68-23.232 53.952-34.816 89.152-34.816 23.68 0 44.352 5.312 62.08 15.936l62.08-62.08c-29.568-23.68-65.92-35.648-108.16-35.648-52.928 0-98.368 18.656-135.296 55.616-36.928 36.928-55.616 82.368-55.616 135.296 0 52.928 18.688 98.368 55.616 135.296 36.928 36.928 82.368 55.616 135.296 55.616 52.928 0 98.368-18.688 135.296-55.616 36.928-36.928 55.616-82.368 55.616-135.296z"
								fill="#1DA1F2"></path>
						</svg></el-icon>
					<el-icon :size="24" class="oauth-icon"><svg viewBox="0 0 1024 1024">
							<path
								d="M512 1024C229.222 1024 0 794.778 0 512S229.222 0 512 0s512 229.222 512 512-229.222 512-512 512zm-35.648-512l-89.152-89.152-89.152 89.152 89.152 89.152 89.152-89.152zm178.304 0l-89.152-89.152-89.152 89.152 89.152 89.152 89.152-89.152z"
								fill="#EA4335"></path>
						</svg></el-icon>
					<el-icon :size="24" class="oauth-icon"><svg viewBox="0 0 1024 1024">
							<path
								d="M512 1024C229.222 1024 0 794.778 0 512S229.222 0 512 0s512 229.222 512 512-229.222 512-512 512zm0-890.304c-208.96 0-378.304 169.344-378.304 378.304 0 208.96 169.344 378.304 378.304 378.304 208.96 0 378.304-169.344 378.304-378.304 0-208.96-169.344-378.304-378.304-378.304zm0 667.648c-159.616 0-289.344-129.728-289.344-289.344 0-159.616 129.728-289.344 289.344-289.344 159.616 0 289.344 129.728 289.344 289.344 0 159.616-129.728 289.344-289.344 289.344z"
								fill="#1877F2"></path>
						</svg></el-icon>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import {
		ref,
		reactive,
		onMounted,
	} from 'vue'
	import {
		ElLoading,
		ElMessage, type FormInstance
	} from 'element-plus'
	import { adminLoginApi, adminRegisterApi } from '@/api/requestapi/Admin.ts'
	import CryptoJS from 'crypto-js'
	import router from '@/router/index.ts'
	import { useCounterStore } from '@/stores/counter.ts'


	onMounted(() => {
		const rememberedUsername = localStorage.getItem('remembered_username')
		if (rememberedUsername) {
			const bytes = CryptoJS.AES.decrypt(rememberedUsername, 'xiongchiwoaini')
			loginForm.username = bytes.toString(CryptoJS.enc.Utf8)
			loginForm.remember = true // 自动勾选复选框
		}
	})

	const store = useCounterStore()

	const activeTab = ref('login')
	const showPhoneLogin = ref(false)

	const loginForm = reactive({
		username: '',
		password: '',
		remember: false,
		role: "shopmanager" // 默认选择店长
	})

	const phoneLoginForm = reactive({
		phone: '',
		captcha: ''
	})

	const registerForm = reactive({
		username: '',
		email: '',
		phoneNumber: '',
		password: '',
		role: 1,
		status: "1",
		confirmPassword: ''
	})

	// 验证码相关状态
	const captchaDisabled = ref(false)
	const captchaBtnText = ref('获取验证码')
	const countdown = ref(60)

	const loginRules = {
		username: [{
			required: true,
			message: '请输入用户名',
			trigger: 'blur'
		}],
		password: [{
			required: true,
			message: '请输入密码',
			trigger: 'blur'
		}]
	}

	const phoneLoginRules = {
		phone: [{
			required: true,
			message: '请输入手机号',
			trigger: 'blur'
		},
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入正确的手机号',
			trigger: 'blur'
		}
		],
		captcha: [{
			required: true,
			message: '请输入验证码',
			trigger: 'blur'
		},
		{
			len: 6,
			message: '验证码长度为6位',
			trigger: 'blur'
		}
		]
	}

	const registerRules = {
		username: [{
			required: true,
			message: '请输入用户名',
			trigger: 'blur'
		},
		{
			min: 3,
			max: 16,
			message: '长度在 3 到 16 个字符',
			trigger: 'blur'
		}
		],
		email: [{
			required: true,
			message: '请输入邮箱',
			trigger: 'blur'
		},
		{
			type: 'email',
			message: '请输入正确的邮箱地址',
			trigger: ['blur', 'change']
		}
		],
		phoneNumber: [{
			required: true,
			message: '请输入手机号',
			trigger: 'blur'
		},
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入正确的手机号',
			trigger: 'blur'
		}
		],
		password: [{
			required: true,
			message: '请输入密码',
			trigger: 'blur'
		},
		{
			min: 6,
			max: 20,
			message: '长度在 6 到 20 个字符',
			trigger: 'blur'
		}
		],
		confirmPassword: [{
			required: true,
			message: '请再次输入密码',
			trigger: 'blur'
		},
		{
			validator: (rule : any, value : any, callback : any) => {
				if (value !== registerForm.password) {
					callback(new Error('两次输入密码不一致!'))
				} else {
					callback()
				}
			},
			trigger: 'blur'
		}
		]
	}

	const loginFormRef = ref()
	const phoneLoginFormRef = ref()
	const registerFormRef = ref()
	// 清除表单校验的红字
	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return
		formEl.resetFields()
	}

	// 获取验证码
	const getCaptcha = async () => {
		await phoneLoginFormRef.value.validateField('phone', valid => {
			if (valid) {
				// 这里添加获取验证码的API调用
				ElMessage.success(`验证码已发送至手机号: ${phoneLoginForm.phone}`)

				// 开始倒计时
				captchaDisabled.value = true
				const timer = setInterval(() => {
					countdown.value--
					captchaBtnText.value = `${countdown.value}秒后重新获取`
					if (countdown.value <= 0) {
						clearInterval(timer)
						captchaDisabled.value = false
						captchaBtnText.value = '获取验证码'
						countdown.value = 60
					}
				}, 1000)
			}
		})
	}

	const handleTabChange = (tab) => {
		// 切换tab时清除所有表单验证
		if (loginFormRef.value) {
			loginFormRef.value.clearValidate()
		}
		if (phoneLoginFormRef.value) {
			phoneLoginFormRef.value.clearValidate()
		}
		if (registerFormRef.value) {
			registerFormRef.value.clearValidate()
		}

		// 如果是切换到登录tab，默认显示账号登录
		if (tab.paneName === 'login') {
			showPhoneLogin.value = false
		}
	}

	const handleLogin = async () => {
		const loading = ElLoading.service({
			lock: true,
			text: '正在登录中...',
			background: 'rgba(0, 0, 0, 0.7)',
		})

		try {
			await loginFormRef.value.validate(async valid => {
				if (!valid) {
					loading.close()
					return false
				}

				if (loginForm.remember) {
					const encrypted = CryptoJS.AES.encrypt(loginForm.username, 'xiongchiwoaini').toString()
					localStorage.setItem("remembered_username", encrypted)
				} else {
					localStorage.removeItem("remembered_username")
				}

				try {
					const res = await adminLoginApi(loginForm)
					if (res.code === 1) { // 使用你的成功code=1
						ElMessage.success(`登录成功! 角色: ${loginForm.role === 'admin' ? '管理员' : '店长'}`)
						await store.setLoginAdmin(res.data)
						await router.push("/")
					} else {
						ElMessage.error(res.msg || '登录失败')
					}
				} catch (error) {
					if (error.response) {
						// 根据后端返回的msg显示错误信息
						ElMessage.error(error.response.data?.msg || '登录失败')
					} else {
						ElMessage.error(error.message || '网络错误')
					}
				} finally {
					loading.close()
				}
			})
		} catch (error) {
			loading.close()
			ElMessage.error('验证失败，请检查表单')
		}
	}

	const handlePhoneLogin = async () => {
		await phoneLoginFormRef.value.validate(async valid => {
			if (valid) {
				ElMessage.success(`手机号登录成功! 角色: ${loginForm.role === 'admin' ? '管理员' : '店长'}`)
				// 这里添加实际的手机号登录逻辑
			} else {
				return false
			}
		})
	}

	const handleRegister = async () => {
		await registerFormRef.value.validate(async valid => {
			if (valid) {
				const res = await adminRegisterApi(registerForm)
				if (res.code) {
					ElMessage.success('注册成功!')
					activeTab.value = 'login'
					// 重置注册表单
					registerFormRef.value.resetFields()
				}

				// 这里添加实际的注册逻辑
			} else {
				return false
			}
		})
	}
</script>

<style scoped>
	.login-container {
		position: relative;
		width: 100vw;
		height: 100vh;
		overflow: hidden;
	}

	.background-image {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-image: url('/src/assets/外卖系统背景图.jpg');
		background-size: cover;
		background-position: center;
		filter: brightness(0.7);
		z-index: 1;
	}

	.auth-box {
		position: absolute;
		top: 50%;
		right: 10%;
		transform: translateY(-50%);
		width: 400px;
		background-color: rgba(255, 255, 255, 0.9);
		border-radius: 8px;
		box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
		padding: 30px;
		z-index: 2;
	}

	.system-title {
		text-align: center;
		color: #333;
		font-size: 24px;
		margin-bottom: 20px;
		font-weight: bold;
	}

	.auth-tabs {
		margin-bottom: 20px;
	}

	:deep(.el-tabs__item) {
		font-size: 18px;
		font-weight: 500;
	}

	.role-selection {
		margin-bottom: 20px;
		text-align: center;
	}

	:deep(.el-radio-group) {
		width: 100%;
	}

	:deep(.el-radio-button) {
		width: 50%;
	}

	:deep(.el-radio-button__inner) {
		width: 100%;
	}

	.auth-button {
		height: 48px;
		font-size: 16px;
		margin-top: 10px;
	}

	.short-button {
		width: 60%;
		margin-left: auto;
		margin-right: auto;
		display: block;
	}

	.login-switch {
		display: flex;
		justify-content: space-between;
		width: 100%;
		margin-top: 10px;
	}

	.forgot-password {
		display: inline-block;
	}

	.captcha-input {
		display: flex;
		gap: 10px;
	}

	.get-captcha-btn {
		width: 120px;
		flex-shrink: 0;
	}

	.third-party-auth {
		margin-top: 30px;
	}

	.divider {
		position: relative;
		text-align: center;
		margin: 20px 0;
	}

	.divider::before {
		content: "";
		position: absolute;
		top: 50%;
		left: 0;
		right: 0;
		height: 1px;
		background-color: #dcdfe6;
		z-index: 1;
	}

	.divider-text {
		position: relative;
		display: inline-block;
		padding: 0 10px;
		background-color: rgba(255, 255, 255, 0.9);
		color: #909399;
		z-index: 2;
	}

	.oauth-icons {
		display: flex;
		justify-content: center;
		gap: 20px;
	}

	.oauth-icon {
		cursor: pointer;
		color: #606266;
		transition: color 0.3s;
	}

	.oauth-icon:hover {
		color: #409eff;
	}
</style>